import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;

public class ListeningService implements Runnable {

    private boolean stop = false;

   PrepareResponse prepareResponse = new PrepareResponse();

    public ListeningService() throws UnknownHostException {
        
    	
    }

    public void stopListening() {
        this.stop = true;
    }



    @Override
    public void run() {
        
    	try {
			new Initialize().initializeSelf();
		} catch (UnknownHostException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        while (!stop) {
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData,
                    receiveData.length);
            try {
                SelfInfo.listeningSocket.receive(receivePacket);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String receivedMsg = new String(receivePacket.getData());
            
                System.out.println("RECEIVED:" + receivedMsg);
                try {
                	
                	prepareResponse.processMessage(receivedMsg);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            
        }
        SelfInfo.listeningSocket.close();
        System.out.println("Listening Socket closed");
    }
}



